/*
Released under this MIT License:
	
Copyright (c) 2010 Bart van der Schoor
	
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
	
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
	
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
package bruce
{

	import flash.display.DisplayObject;

	 /**
	 * 	get a flash-var by name (those also known as swf-object/embed parameters)
	 *	@param name the name of the variable, as set from the html page (or javascript, whatever)
	 *	@param clip any displayObject on the stage (so we can look for the loaderinfo)
	 *	@param alt optionally specify a value to return if variable not set
	 *	@return the value if found, or the alt argument
	 *	@example var userId:String = bruce.getFlashVar(myClip, 'user');
	 *	@author Bart van der Schoor / Bruce
	 *	@version 0.8
	 */
	public function getFlashVar(tagName:String, clip:DisplayObject, alt:*=null):*
	{
		var fn:String = 'getFlashVar() ';

		if (!clip)
		{
			Bruce.arg(fn + Bruce.eclNull);
			return alt;
		}
		if (!clip.root)
		{
			Bruce.arg(fn + clip + ' not on stage');
			return alt;
		}
		if (!tagName)
		{
			Bruce.arg(fn + clip + ' tagName' + Bruce.eEmpty);
			return alt;
		}

		// stage
		try
		{
			// stage first
			if (clip.stage && tagName in clip.stage.loaderInfo.parameters)
			{
				// leaving!
				return clip.stage.loaderInfo.parameters[tagName];
			}
		}
		catch(error:Error)
		{
			// SecurityError probably
			Bruce.log(error);
		}

		try
		{
			if (tagName in clip.root.loaderInfo.parameters)
			{
				// leaving!
				return clip.root.loaderInfo.parameters[tagName];
			}
		}
		catch(error:Error)
		{
			// SecurityError problabably
			Bruce.log(error);
		}
		// more arg?
		Bruce.log(fn + 'no flashVar "' + tagName + '"');

		return alt;
	}
}
